#region " using "

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
//using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Curriculum.Metadatos.ClasesMetadatos;
using Db4objects.Db4o;
using Db4objects.Db4o.Config;
using db4o = Db4objects.Db4o;
using Curriculum.Modelo.Clases;
using Curriculum.Utiles;

#endregion using

namespace Curriculum.Db4oHttpModule
{
    /// <summary>
    /// modulo admnistrador de los requests
    /// encargado de abrir y cerrar la conexion a la base de datos
    /// </summary>
    public class Db4oHttpModule : IHttpModule
    {
        #region Fields

        /// <summary>
        /// cliente de db4o
        /// </summary>
        internal static readonly string clientKey = "db4oClient";

        /// <summary>
        /// servidor de objetos
        /// </summary>
        internal static db4o.IObjectServer objectServer;

        #endregion fields

        #region ctor

        /// <summary>
        /// constructor
        /// </summary>
        static Db4oHttpModule()
        {
        }

        #endregion ctor

        #region IHttpModule Members

        /// <summary>
        /// libera los recursos
        /// </summary>
        public void Dispose()
        {
            if (objectServer != null)
            {
                objectServer.Close();
            }
            objectServer = null;
        }

        /// <summary>
        /// inicio del request
        /// </summary>
        /// <param name="context"></param>
        public void Init(HttpApplication context)
        {           
            context.EndRequest += new EventHandler(context_EndRequest);
        }

        /// <summary>
        /// finaliza el request
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void context_EndRequest(object sender, EventArgs e)
        {
            HttpApplication application = sender as HttpApplication;
            HttpContext context = application.Context;        	
            db4o.IObjectContainer client = context.Items[clientKey] as db4o.IObjectContainer;
            if (client != null)
            {
                client.Close();
            }
            client = null;
            context.Items[clientKey] = null;                       
            Dispose();
        }

        #endregion

        #region Properties

        /// <summary>
        /// devuelve el object server
        /// </summary>
        private static db4o.IObjectServer Server
        {
            get
            {
                HttpContext context = HttpContext.Current;
                if (objectServer == null)
                {
					string yapFile = ConfigurationSettings.AppSettings["DBFileName"];                  
                    objectServer = db4o.Db4oFactory.OpenServer(GetConfiguracion(), context.Server.MapPath(yapFile), 0);
                }
                return objectServer;
            }
        }

        /// <summary>
        /// devuelve el objeto cliente
        /// </summary>
        public static db4o.IObjectContainer Client
        {
            get
            {
                HttpContext context = HttpContext.Current;
                db4o.IObjectContainer client = context.Items[clientKey] as db4o.IObjectContainer;				
                if (client == null)
                {
					string yapFile = ConfigurationSettings.AppSettings["DBFileName"];					
					client = db4o.Db4oFactory.OpenFile(GetConfiguracion(), context.Server.MapPath(yapFile));
                    //client = Server.OpenClient();
                    context.Items[clientKey] = client;
                }
                return client;
            }
        }

        #endregion properties

        #region Methods

        /// <summary>
        /// devuelve los codigos hash del cliente y el servidor
        /// </summary>
        /// <returns></returns>
        public static string HashCodes()
        {
            return string.Format("Server: {0} ; Client :{1}", Server.GetHashCode(), Client.GetHashCode());
        }


		private static IConfiguration GetConfiguracion()
		{			
			IConfiguration configuration = Db4oFactory.NewConfiguration();
			configuration.ActivationDepth(30);			
			configuration.UpdateDepth(30);
			//db4o.Db4oFactory.Configure().OptimizeNativeQueries(true);
//			configuration.ObjectClass(typeof(VersionCurriculo)).CascadeOnActivate(true);			
//			configuration.ObjectClass((typeof(VersionCurriculo))).CascadeOnDelete(true);
//			configuration.ObjectClass((typeof(Antecedente))).CascadeOnDelete(true);
//			configuration.ObjectClass((typeof(Antecedente))).CascadeOnActivate(true);
//			configuration.ObjectClass((typeof(Atributo))).CascadeOnDelete(true);
//			configuration.ObjectClass((typeof(Atributo))).CascadeOnActivate(true);
//			configuration.ObjectClass((typeof(Docente))).CascadeOnDelete(true);
//			configuration.ObjectClass((typeof(Docente))).CascadeOnActivate(true);
//			configuration.ObjectClass(typeof(TipoAntecedentePersistente)).PersistStaticFieldValues();
//			configuration.ObjectClass(typeof(EstadoAntecedentePersistente)).PersistStaticFieldValues();
//			configuration.ObjectClass((typeof(AtributoMetadato))).CascadeOnDelete(true);
//			configuration.ObjectClass((typeof(AtributoMetadato))).CascadeOnActivate(true);

			return configuration;
		}

        #endregion methods
    }
    
}
